using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Caliburn.Micro;

namespace MediaOwl.Core.Modularity
{
    public class LoadModuleList : IResult
    {
        private readonly IModuleManager moduleManager;
        private readonly Action<IEnumerable<Module>> onSuccess;
        private readonly Action<Exception> onFail;

        public LoadModuleList(IModuleManager moduleManager, Action<IEnumerable<Module>> onSuccess, Action<Exception> onFail)
        {
            this.moduleManager = moduleManager;
            this.onSuccess = onSuccess;
            this.onFail = onFail;
        }

        public void Execute(ActionExecutionContext context)
        {
            try
            {
                IList<Module> modules = new List<Module>();
                foreach (var key in Application.Current.Host.InitParams.Keys)
                {
                    if (key.ToLower() == "mediaowl.xap")
                    {
                        continue;
                    }
                    var module = new Module { Uri = new Uri(key, UriKind.Relative) };
                    var name = key.Replace(".xap", "");
                    if (name.ToLower().StartsWith("mediaowl"))
                    {
                        name = name.ToLower().Replace("mediaowl", "");
                    }
                    name = name.Trim(' ', ';', '.');
                    var first = name.FirstOrDefault().ToString().ToUpper();
                    name = first + name.Remove(0, 1);
                    module.Name = name + " Module";

                    modules.Add(module);
                }

                ((ModuleManager)moduleManager).SetModules(modules);
                 if (onSuccess != null)
                     Caliburn.Micro.Execute.OnUIThread(() => onSuccess(modules));

                 Completed(this, new ResultCompletionEventArgs());
            }
            catch (Exception ex)
            {
                if (onFail != null)
                    Caliburn.Micro.Execute.OnUIThread(() => onFail(ex));

                Completed(this, new ResultCompletionEventArgs { Error = ex, WasCancelled = false });
            }

            
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    }
}